package com.example.waterorder.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.waterorder.dto.UserDto;
import com.example.waterorder.entity.User;
import com.example.waterorder.entity.Worker;
import com.example.waterorder.entity.constant.WaterMessage;
import com.example.waterorder.service.UserService;
import com.example.waterorder.service.WechatLoginService;
import com.example.waterorder.service.WorkerService;
import com.example.waterorder.tools.JwtHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class WechatLoginServiceImpl implements WechatLoginService {

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;

    @Resource
    private UserService userService;
    @Resource
    private WorkerService workerService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据前端的code获取用户openId，并判断是否第一次登录及身份
     * 0:用户，1：送水员，2：新用户
     *
     * @param code
     * @return
     */
    @Override
    public UserDto getUserOpenId(String code) {
        String authUrl = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
        authUrl = authUrl + "&appid=" + appId + "&secret=" + secret + "&js_code=" + code;
        String result = HttpUtil.get(authUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        String openId = jsonObject.getStr("openid");
        String session_key = jsonObject.getStr("session_key");
        String token = JwtHelper.createToken(openId);

        User user = userService.selectById(openId);
        Worker worker = workerService.selectById(openId);

        // 将token存入redis
        stringRedisTemplate.opsForValue().set("user:" + token, "exist", 24L, TimeUnit.HOURS);

        if (user == null && worker == null) {
            userService.register(new User(openId));
            return new UserDto(2, WaterMessage.LOGIN_NEW, openId, session_key, token);
        } else {
            if (user != null) {
                return new UserDto(0, WaterMessage.LOGIN_USER, openId, session_key, token);
            } else {
                return new UserDto(1, WaterMessage.LOGIN_WORKER, openId, session_key, token);
            }
        }
    }

    @Override
    public String Test() {
        return appId + "," + secret;
    }
}
